

import React, { useState, useEffect, useRef } from 'react';
import { View, Text, TouchableOpacity, ScrollView, Dimensions, Alert, } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter, useLocalSearchParams } from 'expo-router';
import { FontAwesome5, FontAwesome6 } from '@expo/vector-icons';
import Svg, { Line, Rect, Text as SvgText, G } from 'react-native-svg';
import { GestureDetector, Gesture } from 'react-native-gesture-handler';
import Animated, { useSharedValue, useAnimatedStyle, withTiming, runOnJS, } from 'react-native-reanimated';
import styles from './styles';

interface ProcessNode {
  id: string;
  name: string;
  type: 'start' | 'user' | 'end';
  status: 'completed' | 'current' | 'pending';
  assignee?: string;
  department?: string;
  startTime?: string;
  endTime?: string;
  comment?: string;
  position: { x: number; y: number };
}

interface Connection {
  from: string;
  to: string;
}

interface ProcessData {
  processName: string;
  nodes: ProcessNode[];
  connections: Connection[];
}

const ApprovalFlowScreen: React.FC = () => {
  const router = useRouter();
  const params = useLocalSearchParams();
  const processInstanceId = params.processInstanceId as string || 'default';

  const [isLoading, setIsLoading] = useState(true);
  const [processData, setProcessData] = useState<ProcessData | null>(null);
  const [showTooltip, setShowTooltip] = useState(false);
  const [tooltipData, setTooltipData] = useState<{
    node: ProcessNode;
    position: { x: number; y: number };
  } | null>(null);

  const scale = useSharedValue(1);
  const translateX = useSharedValue(0);
  const translateY = useSharedValue(0);
  const isDragging = useSharedValue(false);

  const screenWidth = Dimensions.get('window').width;
  const screenHeight = Dimensions.get('window').height;

  // 模拟审批流程数据
  const mockProcessData: Record<string, ProcessData> = {
    'default': {
      processName: '员工请假申请流程',
      nodes: [
        {
          id: 'start',
          name: '发起人提交',
          type: 'start',
          status: 'completed',
          assignee: '李小红',
          department: '技术部',
          startTime: '2024-01-15 09:30',
          endTime: '2024-01-15 09:35',
          position: { x: 100, y: 100 }
        },
        {
          id: 'dept_manager',
          name: '部门经理审批',
          type: 'user',
          status: 'completed',
          assignee: '王强',
          department: '技术部',
          startTime: '2024-01-15 09:35',
          endTime: '2024-01-15 10:20',
          comment: '同意请假申请',
          position: { x: 250, y: 100 }
        },
        {
          id: 'hr_approval',
          name: '人事部审批',
          type: 'user',
          status: 'current',
          assignee: '张明',
          department: '人事部',
          startTime: '2024-01-15 10:20',
          position: { x: 400, y: 100 }
        },
        {
          id: 'finance_approval',
          name: '财务部审批',
          type: 'user',
          status: 'pending',
          position: { x: 550, y: 100 }
        },
        {
          id: 'end',
          name: '流程结束',
          type: 'end',
          status: 'pending',
          position: { x: 700, y: 100 }
        }
      ],
      connections: [
        { from: 'start', to: 'dept_manager' },
        { from: 'dept_manager', to: 'hr_approval' },
        { from: 'hr_approval', to: 'finance_approval' },
        { from: 'finance_approval', to: 'end' }
      ]
    }
  };

  useEffect(() => {
    loadProcessData();
  }, [processInstanceId]);

  const loadProcessData = async () => {
    try {
      setIsLoading(true);
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 1000));
      const data = mockProcessData[processInstanceId] || mockProcessData['default'];
      setProcessData(data);
    } catch (error) {
      Alert.alert('错误', '加载流程数据失败');
    } finally {
      setIsLoading(false);
    }
  };

  const handleBackPress = () => {
    if (router.canGoBack()) {
      router.back();
    }
  };

  const handleNodePress = (node: ProcessNode, event: any) => {
    const { pageX, pageY } = event.nativeEvent;
    setTooltipData({
      node,
      position: { x: pageX, y: pageY }
    });
    setShowTooltip(true);

    // 3秒后自动隐藏tooltip
    setTimeout(() => {
      setShowTooltip(false);
    }, 3000);
  };

  const hideTooltip = () => {
    setShowTooltip(false);
  };

  const handleZoomIn = () => {
    if (scale.value < 3) {
      scale.value = withTiming(scale.value + 0.2, { duration: 200 });
    }
  };

  const handleZoomOut = () => {
    if (scale.value > 0.5) {
      scale.value = withTiming(scale.value - 0.2, { duration: 200 });
    }
  };

  const handleZoomReset = () => {
    scale.value = withTiming(1, { duration: 300 });
    translateX.value = withTiming(0, { duration: 300 });
    translateY.value = withTiming(0, { duration: 300 });
  };

  const panGesture = Gesture.Pan()
    .onBegin(() => {
      isDragging.value = true;
    })
    .onUpdate((event) => {
      translateX.value += event.translationX - event.previousTranslationX;
      translateY.value += event.translationY - event.previousTranslationY;
    })
    .onEnd(() => {
      isDragging.value = false;
    })
    .onFinalize(() => {
      isDragging.value = false;
    });

  const animatedStyle = useAnimatedStyle(() => {
    return {
      transform: [
        { scale: scale.value },
        { translateX: translateX.value / scale.value },
        { translateY: translateY.value / scale.value }
      ],
    };
  });

  const getNodeIcon = (type: string): string => {
    switch (type) {
      case 'start':
        return 'plus';
      case 'end':
        return 'check';
      default:
        return 'user-circle';
    }
  };

  const getNodeStatusStyle = (status: string) => {
    switch (status) {
      case 'completed':
        return styles.nodeCompleted;
      case 'current':
        return styles.nodeCurrent;
      default:
        return styles.nodePending;
    }
  };

  const getNodeTextColor = (status: string): string => {
    return status === 'pending' ? '#6B7280' : '#FFFFFF';
  };

  const getLineStatusStyle = (toNodeStatus: string) => {
    if (toNodeStatus === 'completed') {
      return styles.lineCompleted;
    } else if (toNodeStatus === 'current') {
      return styles.lineCurrent;
    }
    return styles.linePending;
  };

  const renderTooltip = () => {
    if (!showTooltip || !tooltipData) return null;

    const { node, position } = tooltipData;
    
    // 计算tooltip位置，确保不超出屏幕
    let tooltipX = position.x + 20;
    let tooltipY = position.y - 100;
    
    if (tooltipY < 100) tooltipY = 100;
    if (tooltipX + 200 > screenWidth) tooltipX = screenWidth - 220;

    return (
      <View
        style={[
          styles.tooltip,
          {
            left: tooltipX,
            top: tooltipY,
          }
        ]}
      >
        <Text style={styles.tooltipTitle}>{node.name}</Text>
        <View style={styles.tooltipContent}>
          {node.status === 'completed' && (
            <>
              <Text style={styles.tooltipText}>
                处理人：{node.assignee} ({node.department})
              </Text>
              <Text style={styles.tooltipText}>
                开始时间：{node.startTime}
              </Text>
              <Text style={styles.tooltipText}>
                完成时间：{node.endTime}
              </Text>
              {node.comment && (
                <Text style={styles.tooltipText}>
                  审批意见：{node.comment}
                </Text>
              )}
            </>
          )}
          {node.status === 'current' && (
            <>
              <Text style={styles.tooltipText}>
                当前处理人：{node.assignee} ({node.department})
              </Text>
              <Text style={styles.tooltipText}>
                开始时间：{node.startTime}
              </Text>
              <Text style={styles.tooltipText}>等待处理中...</Text>
            </>
          )}
          {node.status === 'pending' && (
            <Text style={styles.tooltipText}>等待处理中...</Text>
          )}
        </View>
      </View>
    );
  };

  const getCurrentNode = (): ProcessNode | null => {
    return processData?.nodes.find(node => node.status === 'current') || null;
  };

  if (isLoading) {
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.header}>
          <TouchableOpacity style={styles.backButton} onPress={handleBackPress}>
            <FontAwesome6 name="arrow-left" size={18} color="#1F2937" />
          </TouchableOpacity>
          <Text style={styles.headerTitle}>审批流程</Text>
          <View style={styles.headerPlaceholder} />
        </View>
        <View style={styles.loadingContainer}>
          <View style={styles.loadingSpinner} />
          <Text style={styles.loadingText}>正在加载流程图...</Text>
        </View>
      </SafeAreaView>
    );
  }

  if (!processData) {
    return (
      <SafeAreaView style={styles.container}>
        <View style={styles.header}>
          <TouchableOpacity style={styles.backButton} onPress={handleBackPress}>
            <FontAwesome6 name="arrow-left" size={18} color="#1F2937" />
          </TouchableOpacity>
          <Text style={styles.headerTitle}>审批流程</Text>
          <View style={styles.headerPlaceholder} />
        </View>
        <View style={styles.errorContainer}>
          <Text style={styles.errorText}>加载流程数据失败</Text>
          <TouchableOpacity style={styles.retryButton} onPress={loadProcessData}>
            <Text style={styles.retryButtonText}>重试</Text>
          </TouchableOpacity>
        </View>
      </SafeAreaView>
    );
  }

  const currentNode = getCurrentNode();

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity style={styles.backButton} onPress={handleBackPress}>
          <FontAwesome6 name="arrow-left" size={18} color="#1F2937" />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>审批流程</Text>
        <View style={styles.headerPlaceholder} />
      </View>

      <View style={styles.mainContent}>
        <GestureDetector gesture={panGesture}>
          <Animated.View style={[styles.flowContainer, animatedStyle]}>
            <Svg
              width={screenWidth}
              height={screenHeight - 200}
              viewBox="0 0 800 600"
              preserveAspectRatio="xMidYMid meet"
            >
              {/* 绘制连接线 */}
              {processData.connections.map((connection, index) => {
                const fromNode = processData.nodes.find(node => node.id === connection.from);
                const toNode = processData.nodes.find(node => node.id === connection.to);
                
                if (!fromNode || !toNode) return null;

                return (
                  <Line
                    key={`connection-${index}`}
                    x1={fromNode.position.x + 40}
                    y1={fromNode.position.y + 25}
                    x2={toNode.position.x}
                    y2={toNode.position.y + 25}
                    strokeWidth={3}
                    {...getLineStatusStyle(toNode.status)}
                  />
                );
              })}

              {/* 绘制节点 */}
              {processData.nodes.map((node) => (
                <G
                  key={node.id}
                  transform={`translate(${node.position.x}, ${node.position.y})`}
                >
                  <TouchableOpacity
                    onPress={(event) => handleNodePress(node, event)}
                    activeOpacity={0.8}
                  >
                    <Rect
                      width={80}
                      height={50}
                      rx={8}
                      ry={8}
                      {...getNodeStatusStyle(node.status)}
                    />
                    <SvgText
                      x={15}
                      y={35}
                      fontFamily="FontAwesome"
                      fontSize={20}
                      fill={getNodeTextColor(node.status)}
                    >
                      {getNodeIcon(node.type)}
                    </SvgText>
                    <SvgText
                      x={50}
                      y={35}
                      textAnchor="middle"
                      fontSize={12}
                      fill={getNodeTextColor(node.status)}
                      fontWeight="500"
                    >
                      {node.name}
                    </SvgText>
                  </TouchableOpacity>
                </G>
              ))}
            </Svg>
          </Animated.View>
        </GestureDetector>

        {/* 缩放控制按钮 */}
        <View style={styles.zoomControls}>
          <TouchableOpacity style={styles.zoomButton} onPress={handleZoomIn}>
            <FontAwesome6 name="plus" size={16} color="#1F2937" />
          </TouchableOpacity>
          <TouchableOpacity style={styles.zoomButton} onPress={handleZoomOut}>
            <FontAwesome6 name="minus" size={16} color="#1F2937" />
          </TouchableOpacity>
          <TouchableOpacity style={styles.zoomButton} onPress={handleZoomReset}>
            <FontAwesome5 name="expand-arrows-alt" size={16} color="#1F2937" />
          </TouchableOpacity>
        </View>

        {/* 当前节点信息卡片 */}
        {currentNode && (
          <View style={styles.currentNodeInfo}>
            <View style={styles.currentNodeCard}>
              <View style={styles.currentNodeContent}>
                <View style={styles.currentNodeIndicator} />
                <View style={styles.currentNodeDetails}>
                  <Text style={styles.currentNodeLabel}>当前节点</Text>
                  <Text style={styles.currentNodeName}>{currentNode.name}</Text>
                </View>
                <View style={styles.currentNodeAssignee}>
                  <Text style={styles.currentNodeAssigneeLabel}>处理人</Text>
                  <Text style={styles.currentNodeAssigneeName}>{currentNode.assignee}</Text>
                </View>
              </View>
            </View>
          </View>
        )}

        {/* 节点信息提示框 */}
        {renderTooltip()}
      </View>
    </SafeAreaView>
  );
};

export default ApprovalFlowScreen;

